﻿using CommunityToolkit.Mvvm.Messaging;
using MetaView.Core1;
using MetaView.Ticket.Tools.Helper;
using MetaView.Ticket.ViewModels.Pages;
using MetaView.Ticket.ViewModels.Windows;
using MetaView.Ticket.Views.Pages;
using MetaView.Ticket.Views.Windows;
using Microsoft.Extensions.DependencyInjection;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows;
using Wpf.Ui;

namespace MetaView.Ticket
{
    public partial class App
    {
        //是否是设计时
        public static readonly bool IsDesignTime = DesignerProperties.GetIsInDesignMode(new DependencyObject());

        //IOC容器
        public IServiceProvider Services { get; }

        public new static App Current => (App)Application.Current;

        public App()
        {
            Services = ConfigureServices();

            #region 全局异常捕获

            //UI线程未捕获异常处理事件（UI主线程）
            this.DispatcherUnhandledException += (s, e) =>
            {
                if (e.Exception is Exception ex)
                {
                    LogHelper.Istance.Write($"{ex.ToString()}");
                    e.Handled = true;//表示异常已处理，可以继续运行
                }
            };

            //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                if (e.ExceptionObject is Exception ex)
                    LogHelper.Istance.Write(ex.ToString());
            };

            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += (s, e) =>
            {
                if (e.Exception is Exception ex)
                {
                    LogHelper.Istance.Write($"{ex.ToString()}");
                    e.SetObserved(); // 标记异常已被处理，避免程序崩溃
                }
            };

            #endregion

            #region 单实例运行

            //判断程序是否已经启动
            var ProcessName = Assembly.GetExecutingAssembly().GetName().Name;//程序集名称
            Process currentProcess = Process.GetCurrentProcess();//当运行的新进程

            // 通过程序集名称判断是否有进程已运行
            Process[] ps = Process.GetProcessesByName(ProcessName);

            // 因为新进程名也是ProcessName，所以ps的Length大于1时才是有多个进程
            if (ps.Length > 1)
            {
                foreach (var item in ps)
                {
                    // 找到非当前新进程的 MessageConstruction 进程对象
                    if (item.Id != currentProcess.Id)
                    {
                        //关闭之前的进程
                        item.Kill();
                    }
                }
            }

            #endregion 单实例运行    
        }

        //容器注册
        private static IServiceProvider ConfigureServices()
        {
            var services = new ServiceCollection();

            services.AddSingleton<MainWindowView>();
            services.AddSingleton<MainWindowViewModel>();

            services.AddSingleton<INavigationService, NavigationService>();
            services.AddSingleton<ISnackbarService, SnackbarService>();
            services.AddSingleton<IContentDialogService, ContentDialogService>();

            services.AddSingleton<DashboardPage>();
            services.AddSingleton<DashboardViewModel>();

            services.AddSingleton<DataPage>();
            services.AddSingleton<DataPageViewModel>();

            services.AddSingleton<SettingsPage>();
            services.AddSingleton<SettingsViewModel>();

            LoadPlugins(services);

            return services.BuildServiceProvider();
        }

        public static void LoadPlugins(IServiceCollection services)
        {
            string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string[] pluginFiles = Directory.GetFiles(appDirectory, "MetaView.Module.*.dll");
            foreach (var pluginFile in pluginFiles)
            {
                var assembly = Assembly.LoadFrom(pluginFile);
                foreach (var type in assembly.GetExportedTypes())
                {
                    try
                    {
                        if (typeof(IPluginModule).IsAssignableFrom(type))
                        {
                            var plugin = (IPluginModule)Activator.CreateInstance(type);
                            var template = new DataTemplate(plugin.GetViewModel().GetType())
                            {
                                VisualTree = new FrameworkElementFactory(plugin.GetViewType())
                            };
                            services.AddSingleton(type);
                            //Application.Current.Resources.Add(
                            //    new DataTemplateKey(plugin.GetViewModel().GetType()),
                            //    template);

                            //WeakReferenceMessenger.Default.Send(
                            //    new PluginLoadedMessage(plugin.GetViewModel()));
                        }
                    }
                    catch (Exception ex)
                    {
                        // 记录加载插件时发生的异常
                        LogHelper.Istance.Write($"加载插件时发生错误: {ex}");
                    }
                }
            }
        }



        //private static void LoadPlugins(IServiceCollection services)
        //{
        //    string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        //    string[] pluginFiles = Directory.GetFiles(appDirectory, "MetaView.Module.*.dll");

        //    foreach (var pluginFile in pluginFiles)
        //    {
        //        try
        //        {
        //            var assembly = Assembly.LoadFrom(pluginFile);
        //            var types = assembly.GetTypes();

        //            foreach (var type in types)
        //            {
        //                if (type.IsClass && !type.IsAbstract && !type.IsInterface)
        //                {
        //                    // 假设插件需要实现某个特定的接口，例如 IPlugin
        //                    if (typeof(IPluginModule).IsAssignableFrom(type))
        //                    {
        //                        services.AddSingleton(type);
        //                    }
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            // 记录加载插件时发生的异常
        //            LogHelper.Istance.Write($"加载插件时发生错误: {ex}");
        //        }
        //    }
        //}

        /// <summary>
        /// 程序启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var navigationWindow = Services.GetService<MainWindowView>();
            navigationWindow!.Loaded += OnNavigationWindowLoaded;
            navigationWindow.Show();
            
            //记录软件启动模式
            string AppName = AppDomain.CurrentDomain.FriendlyName;

#if DEBUG
            LogHelper.Istance.Write($"软件 {AppName} 以 Debug 模式启动！");
#else
            LogHelper.Istance.Write($"软件 {AppName} 以 Release 模式启动！");
#endif
        }

        /// <summary>
        /// 默认加载第一项page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNavigationWindowLoaded(object sender, RoutedEventArgs e)
        {
            if (sender is not MainWindowView navigationWindow) { return; }
            navigationWindow.NavigationView.Navigate(typeof(DashboardPage));
        }

    }
}
